package ltaa.sponsoredsearch.GAM;

import java.io.FileReader;
import java.io.BufferedReader;


class BidsParser{
	private String filename;
	private Bidder[] bidders;
	private int totItems;

	
	public BidsParser(String file) {
		this.filename = file;
		bidders = null;
		totItems = 0;
	}

	public void parse() {
		try {
			BufferedReader fin = new BufferedReader(new FileReader(filename));

			String line = fin.readLine();

			int biddersQty = 0;
			totItems = 0;


			if (line != null) {
				String[] globalinfo = line.split(" ");
				biddersQty = Integer.parseInt(globalinfo[0]);
				totItems = Integer.parseInt(globalinfo[1]);
			}

			line = fin.readLine();

			int bidIndex = 0;
			bidders = new Bidder[biddersQty];

			while (line != null) {
				if (bidIndex >= biddersQty) System.err.println("Inconsistent number of bidders");
				if (line.startsWith("#")) {
					continue;
				}
				bidders[bidIndex] = getBidder(bidIndex, line, totItems);
				bidIndex++;
				line = fin.readLine();
			}

		} catch (java.io.FileNotFoundException e) {
			System.out.println("File "+filename+" couldn't be found.");
			System.exit(-1);
		} catch (java.io.IOException e) {
			System.out.println("There was an error while reading the file.");
			e.printStackTrace();
		}
	}

	private Bidder getBidder(int pos, String line, int itemsQty) {
		String[] bidderDef = line.split(" ");
		if (bidderDef.length != (itemsQty+2))
			System.err.println("Inconsistent number of valuations.");
		double[] vals = new double[itemsQty];
		double[] maxs = new double[itemsQty];
		int noItems = Integer.parseInt(bidderDef[0]);
		double budget = Double.parseDouble(bidderDef[1]);

		for (int i = 2; i < bidderDef.length; i++) {
			int splitAt = bidderDef[i].indexOf(':');
			if (splitAt == -1) {
				double val = Double.parseDouble(bidderDef[i]);
				vals[i-2] = val;
				maxs[i-2] = val;
			} else {
				vals[i-2] = Double.parseDouble(bidderDef[i].substring(0,splitAt));
				maxs[i-2] = Double.parseDouble(bidderDef[i].substring(splitAt+1));
			}
		}

		return new Bidder(pos, noItems, budget, vals, maxs);
	}

	public Bidder[] getBidders() {
		return bidders;
	}

	public int getTotItems() {
		return totItems;
	}

}
